﻿using System;
using System.Runtime.InteropServices;
using System.Threading;
using Google.GData.Client;
using Google.GData.Extensions.Location;
using Google.GData.YouTube;
using Google.GData.Extensions.MediaRss;
using Google.YouTube;

namespace Desktop.Media.Encoder
{
    [ClassInterface(ClassInterfaceType.AutoDispatch)]
    [ComVisible(true)]
    public class YouTubeUploader
    {
        private const string DEVELOPER_KEY = "AI39si7PV6MvlTJsyfVKvnDYOjLTenj8Fg5pDk4J0Pf92wr5aIlIPfv3MhEYy_DZSGRWGjiPckpyyzmy5AWwj2_jWYxKmfjHJQ";

        public bool Completed
        {
            get; private set;
        }

        public bool Failed
        {
            get; private set;
        }

        public void Upload(string username, string password, string title, string filepath)
        {
            Completed = false;
            Failed = false;

            var t = new Thread((ThreadStart)delegate
            {
                var settings = new YouTubeRequestSettings("YouTube Uploader", DEVELOPER_KEY, username, password);
                var request = new YouTubeRequest(settings);

                var newVideo = new Video();

                newVideo.Title = title;
                newVideo.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema));
                newVideo.Keywords = "Mix10";
                newVideo.Description = "Mix10 Youtube Uploader";
                newVideo.YouTubeEntry.Private = false;
                newVideo.Tags.Add(new MediaCategory("mydevtag, anotherdevtag", YouTubeNameTable.DeveloperTagSchema));

                newVideo.YouTubeEntry.Location = new GeoRssWhere(37, -122);
                newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA");
                newVideo.YouTubeEntry.MediaSource = new MediaFileSource(filepath, "video/quicktime");

                try
                {
                    Video createdVideo = request.Upload(newVideo);
                    Completed = true;
                    Failed = false;
                }
                catch (Exception)
                {
                    Completed = true;
                    Failed = true;
                    return;
                }
            });

            t.Start();
        }
    }
}
